package com.supreme.secretserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.supreme.commonboot.exception.BizException;
import com.supreme.commonboot.utils.AjaxResp;
import com.supreme.secretserver.props.BaseConfigProps;
import com.supreme.secretserver.props.EncryptProps;
import com.supreme.secretserver.utils.AESUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "test")
public class TestController {

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private EncryptProps encryptProps;

    @Resource
    private BaseConfigProps baseConfigProps;

    @GetMapping(value = "hello")
    public AjaxResp hello() {
        return AjaxResp.instance("hello");
    }

    @GetMapping(value = "request")
    public AjaxResp requestInfo() {
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        String requestURI = httpServletRequest.getRequestURI();
        String localAddr = httpServletRequest.getLocalAddr();
        String remoteAddr = httpServletRequest.getRemoteAddr();
        JSONObject resultJson = new JSONObject()
                .fluentPut("requestURL", requestURL.toString())
                .fluentPut("requestURI", requestURI).fluentPut("localAddr", localAddr)
                .fluentPut("remoteAddr", remoteAddr);
        return AjaxResp.instance(resultJson);
    }

    @GetMapping(value = "configUsername")
    public AjaxResp configUsername() {
        return AjaxResp.instance(baseConfigProps.getUsername());
    }

    @GetMapping(value = "configPassword")
    public AjaxResp configPassword() {
        return AjaxResp.instance(baseConfigProps.getPassword());
    }

    @GetMapping(value = "encrypt")
    public AjaxResp encryptTest(@RequestParam(value = "message") String message) throws Exception {
        String encryptKey = encryptProps.getAesKey();
        System.out.println("message = " + message);
        String encrypt = AESUtils.encrypt(message.getBytes(), encryptProps.getAesKeyBytes());
        System.out.println("encrypt = " + encrypt);
        byte[] decrypt = AESUtils.decrypt(encrypt.getBytes(), encryptProps.getAesKeyBytes());
        final String decryptData = new String(decrypt);
        System.out.println("decryptData = " + decryptData);
        return AjaxResp.instance(decryptData).append("encryptKey", encryptKey);
    }

    @GetMapping(value = "exception")
    public AjaxResp exception(@RequestParam(value = "exception", required = false) String exception) {
        if (StringUtils.isNotBlank(exception)) {
            throw new BizException("bizException: " + exception);
        }
        return AjaxResp.instance();
    }
}
